/**
 * Independent time operation tool to facilitate subsequent switch to dayjs
 */
import dayjs from 'dayjs'

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const DATE_FORMAT = 'YYYY-MM-DD'

export function formatToDateTime(date?: dayjs.ConfigType, format = DATE_TIME_FORMAT): string {
  return dayjs(date).format(format)
}

export function formatToDate(date?: dayjs.ConfigType, format = DATE_FORMAT): string {
  return dayjs(date).format(format)
}

export const dateUtil = dayjs

export const formatTime = (time: string | number | Date, fmt: string): string => {
  if (!time) return ''
  const date = new Date(time)
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds(),
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        // @ts-ignore: Unreachable code error
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
      )
    }
  }
  return fmt
}

export function getYearWeek(date: Date = new Date()): string {
  const year = date.getFullYear();
  const week = getWeekOfYear(date);
  return `${year}-${week}`;
}

function getWeekOfYear(date: Date): number {
  const tempDate = new Date(date.valueOf());
  tempDate.setHours(0, 0, 0, 0);
  tempDate.setDate(1);
  tempDate.setMonth(0);
  const dayOfYear = (date.getTime() - tempDate.getTime()) / 86400000;
  return Math.ceil((dayOfYear + tempDate.getDay() + 1) / 7);
}

export function getLastWeek(): string {
  const lastWeekDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  return getYearWeek(lastWeekDate);
}

export function getLastLastWeek(): string {
  const lastLastWeekDate = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000);
  return getYearWeek(lastLastWeekDate);
}

export const getLastWeekRange = () => {
  const startOfLastWeek = dayjs().startOf('week').subtract(7, 'day'); // 上周的第一天（周日）
  const startOfTwoWeeksAgo = dayjs().startOf('week').subtract(14, 'day'); // 上上周的第一天（周日）

  // 格式化为 GGGG-wo
  const endWeek = startOfLastWeek.format('GGGG-[W]wo'); // 上周的起始周数
  // 格式化为 GGGG-wo
  const startWeek = startOfTwoWeeksAgo.format('GGGG-[W]wo'); // 上上周的起始周数

  return [startWeek, endWeek];
};